import os
import shutil
import codecs
import chardet


def create_dirs(path):
    shutil.rmtree(path)
    if not os.path.exists(path):
        os.makedirs(path)


def list_files_and_dirs(path):
    file_list = []
    dir_list = []
    for root, directories, files in os.walk(path):
        for filename in files:
            file_list.append(os.path.join(root, filename))
        for directory in directories:
            # 替换第一级路径为 "opt"
            rel_path = os.path.relpath(os.path.join(root, directory), path)

            # 在 Windows 中使用反斜杠表示路径分隔符
            new_dir = os.path.join(os.getcwd(), "opt",
                                   os.path.sep.join(rel_path.split(os.path.sep)[1:]).replace('/', '\\'))

            # 递归创建不存在的目录
            create_dirs(new_dir)
            dir_list.append(new_dir)
    return file_list, dir_list


def get_c_and_h_files(folder_path):
    """
    遍历指定文件夹及其子目录，获取所有的C文件和h文件路径
    """
    c_and_h_files = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith(".c") or file.endswith(".h"):
                c_and_h_files.append(os.path.join(root, file))
    return c_and_h_files


def convert_encoding(file_path, new_encoding='utf-8', line_ending='\n'):
    """
    将文件重新编码为指定的字符集，默认为 UTF-8
    并将行尾符转换为指定格式，默认为 \n
    """
    with open(file_path, 'rb') as f:
        content = f.read()
        old_encoding = chardet.detect(content)['encoding']  # 探测文件实际编码
        if old_encoding is None:
            print(f"无法探测文件 {file_path} 的编码")
            with open(file_path, 'wb', encoding=new_encoding, newline='') as fp:
                fp.write(content)
                fp.close()
                f.close()
        f.close()
    with open(file_path, 'w', encoding=new_encoding, newline='') as f:
        try:
            decoded_content = content.decode(old_encoding)
        except UnicodeDecodeError:
            decoded_content = content.decode(old_encoding, errors='ignore')
        encoded_content = decoded_content.encode(new_encoding, errors='ignore')
        lines = encoded_content.decode(new_encoding).split('\n')
        # 去除每一行结尾的换行符，并统一使用指定的行尾符
        lines = [line.rstrip() for line in lines]
        f.write(line_ending.join(lines))
        f.close()


if __name__ == '__main__':
    # 指定要遍历的目录路径
    path = '.\\src'
    opt = '.\\opt'

    shutil.rmtree(opt, ignore_errors=True)
    shutil.copytree(path, opt)

    result = get_c_and_h_files(opt)
    # 打印结果
    print(result)

    i = 0
    len_res = len(result)
    for file in result:
        convert_encoding(file)
        print(str(i) + "/" + str(len_res))
        i = i + 1
    print("finish with no error")
